package com.leetcode.LC_MED;

import java.util.Arrays;

public class LC16 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int min = nums[0]+nums[1]+nums[2]-target;
        for (int i = 0; i < nums.length - 2; i++) {
            int start = i+1;
            int end = nums.length-1;
            while (start!=end){
                int sum = nums[i]+nums[start]+nums[end];
                if (Math.abs(target-min)>Math.abs(target-sum)){
                    min = sum;
                }
                if (sum>target){
                    end--;
                }else if(sum<target){
                    start++;
                }else {
                    return target;
                }
            }
        }
        return min;
    }

    public static void main(String[] args) {
        LC16 lc16 = new LC16();
        // System.out.println(lc16.threeSumClosest(new int[]{-1, 2, 1, -4}, 1));
        int i = lc16.threeSumClosest(new int[]{-3, -2, -5, 3, -4}, -1);
        System.out.println(i);
    }
}
